import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import UpgradePackageForm from './components/UpgradePackageForm';

import * as c from '@/services/consts';
import * as api from '@/services/upgradePackage';
import * as utils from '@/utils/utils';
import { PageContainer } from '@ant-design/pro-components';

const UpgradePackageList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.UpgradePackageModel | undefined>(
    undefined,
  );

  const [productId, setProductId] = useState<string | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductMenuItems } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductMenuItems: model.getProductMenuItems,
    }),
  );

  const productMenuItems = getProductMenuItems(true);

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);
    return Promise.resolve(result);
  };

  const handleFormSubmit = async (record: API.UpgradePackageModel) => {
    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: number) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.UpgradePackageModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: true,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '平台',
      width: 140,
      dataIndex: 'platform',
      sorter: true,
    },
    {
      title: '渠道',
      align: 'center',
      width: 100,
      dataIndex: 'channel',
      sorter: true,
    },
    {
      title: '版本号',
      align: 'center',
      width: 100,
      dataIndex: 'ver',
      sorter: true,
    },
    {
      title: '名称',
      width: 160,
      dataIndex: 'name',
      sorter: true,
    },
    {
      title: '更新包地址',
      dataIndex: 'url',
      sorter: true,
    },
    {
      title: '用户等级',
      width: 160,
      sorter: true,
      renderText: (_, record) => {
        let levelsText = '';
        for (let i = 0; i < record.policyConfig.memberLevels?.length; i++) {
          if (levelsText != '') {
            levelsText += ',';
          }
          levelsText += c.getMemberLevelText(
            record.policyConfig.memberLevels[i],
          );
        }
        return levelsText;
      },
    },
    {
      title: '版本条件',
      align: 'center',
      width: 100,
      sorter: false,
      render: (_, record) => {
        // if (
        //   record.policy?.platformAppVerCompares == null ||
        //   record.policy?.platformAppVerCompares.length < 1
        // ) {
        //   return <></>;
        // }

        let lines = [];

        if (
          record.policyConfig != null &&
          record.policyConfig.appVerCompareMode &&
          record.policyConfig.appVerCompareMode != '' &&
          record.policyConfig.appVer &&
          record.policyConfig.appVer > 0
        ) {
          lines.push(
            <span>
              {record.policyConfig.appVerCompareMode}
              {record.policyConfig.appVer}

              <br />
            </span>,
          );
        }

        return lines;

        // if (
        //   record.policy != null &&
        //   record.policy.appVerCompare &&
        //   record.policy.appVerCompare != '' &&
        //   record.policy.appVer > 0
        // ) {
        //   return `${record.policy.appVerCompare}${record.policy.appVer}`;
        // }
        // return null;
      },
    },
    {
      title: '按比例升级',
      align: 'center',
      width: 100,
      dataIndex: 'partialUpgrade',
      sorter: false,
      renderText: (_, record) => {
        if (record.partialUpgrade == true) {
          return record.partialUpgradePercent;
        }
        return null;
      },
    },
    {
      title: '间隔提醒(小时)',
      align: 'center',
      width: 120,
      dataIndex: 'reminderInterval',
      sorter: false,
      renderText: (_, record) => {
        if (record.reminderInterval == true) {
          return record.reminderIntervalTimes;
        }
        return null;
      },
    },

    {
      title: '指定用户',
      dataIndex: 'forceUsers',
      sorter: false,
      renderText: (_, record) => {
        return record.forceUsers?.replaceAll('\n', ' ');
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: '修改时间',
      align: 'center',
      width: 220,
      dataIndex: 'updateTime',
      sorter: true,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.updateTime);
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('upgradepackage_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('upgradepackage_delete')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        search={false}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
          // current: pageCurrent,
          // total: totalCount,
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              //console.log('tabKey', tabKey);
              setProductId(tabKey as string);

              // actionRef.current?.reset();
            },
          },
        }}
        toolBarRender={() => {
          if (hasRight('upgradepackage_create')) {
            return [
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ];
          }
          return [];
        }}
        columns={columns}
        params={{
          productId:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
        }}
        request={loadData}
      />
      <UpgradePackageForm
        visible={formVisible}
        defaultProductId={
          productId && productId !== c.DefaultOptionAll.key
            ? parseInt(productId)
            : undefined
        }
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default UpgradePackageList;
